package com.linkhub.oms.admin.common.util.EnumValueConstraintUtil;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
 * @ClassName EnumValueConstraintValidator
 * @Description: com.linkhub.oms.admin.common.util.EnumValueConstraintUtil
 * @Author: Jaycle
 * @CreateDate: 2024/11/23 21:30
 * @Version: 1.0
 */

public class EnumValueConstraintValidator implements ConstraintValidator<EnumValueConstraint, Object> {

    private Class<? extends Enum<?>> enumClass;
    private String fieldName;
    private Set<String> excludedValues;

    @Override
    public void initialize(EnumValueConstraint constraint) {
        this.enumClass = constraint.enumClass();
        this.fieldName = constraint.field();
        this.excludedValues = new HashSet<>(Arrays.asList(constraint.excludedValues()));
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (value == null) {
            return true; // 空值的处理交给其他注解
        }

        try {
            for (Enum<?> enumConstant : enumClass.getEnumConstants()) {
                Field field = enumClass.getDeclaredField(fieldName);
                field.setAccessible(true);
                Object fieldValue = field.get(enumConstant);

                // 如果排除值为空，则所有枚举值均有效
                if (excludedValues.isEmpty() || !excludedValues.contains(String.valueOf(fieldValue))) {
                    if (String.valueOf(fieldValue).equals(String.valueOf(value))) {
                        return true;
                    }
                }
            }
        } catch (NoSuchFieldException | IllegalAccessException e) {
            throw new RuntimeException("Invalid field or enum configuration in annotation: " + fieldName, e);
        }

        return false; // 不符合条件的值无效
    }
}
